package Algorithm.LinkedListProblem;

/**
 * @Author cj
 * @Date 2021/11/23 20:41
 */
public class isPalindrome {

    static class Node {
        public int value;
        public Node next;

        public Node(int val) {
            this.value = val;
        }
    }

    // 方法1：利用栈，一个个比较，空间复杂度：O(n)

    // 方法2：找中点，拆开，反转，比较，空间复杂度：O(1)
    public static boolean isPalindrome2(Node head) {
        if (head == null || head.next == null) {
            return true;
        }
        // 两个节点情况
        if (head.next.next == null) {
            return head.value == head.next.value;
        }
        Node right = head.next;
        Node cur = head;
        Node pre = null;
        while (cur.next != null && cur.next.next != null) {
            pre = right;
            right = right.next;
            cur = cur.next.next;
        }
        pre.next = null;
        // 反转第二部分
        pre = null;
        cur = null;
        while (right != null) {
            cur = right.next;
            right.next = pre;
            pre = right;
            right = cur;
        }
        // 比较(pre是第二部分反转后的第一个节点)
        cur = head; right = pre;
        while (cur != null && right != null) {
            if (cur.value != right.value) {
                return false;
            }
            cur = cur.next;
            right = right.next;
        }
        return true;
    }

    // 方法3：右半区反转，指向中点，逐个比较。空间复杂度O(1)
    public static boolean isPalindrome3(Node head) {
        if (head == null || head.next == null) {
            return true;
        }
        boolean res = true;
        Node n1 = head;
        Node n2 = head;
        while (n2.next != null && n2.next.next != null) {
            n1 = n1.next;
            n2 = n2.next.next;
        }
        n2 = n1.next; // 此时n1是中点,n2指向右半部分第一个节点
        n1.next = null;
        Node n3 = null;
        // 右半区反转
        while (n2 != null) {
            n3 = n2.next;
            n2.next = n1;
            n1 = n2;
            n2 = n3;
        }
        n3 = n1; // n3指向最后一个节点
        n2 = head;
        // 检查回文
        while (n1 != null && n2 != null) {
            if (n1.value != n2.value) {
                res = false;
                break;
            }
            n1 = n1.next;
            n2 = n2.next;
        }
        // 恢复链表
        n1 = n3.next;
        n3.next = null;
        while (n1 != null) {
            n2 = n1.next;
            n1.next = n3;
            n3 = n1;
            n1 = n2;
        }
        return res;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        System.out.println(isPalindrome3(head));
        while (head != null) {
            System.out.println(head.value);
            head = head.next;
        }
    }
}
